package com.yida.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.yida.bean.blog;
import com.yida.bean.blogtype;
import com.yida.service.serverblog;

@Controller
public class type {

	@Autowired
	public serverblog service;
	
	@RequestMapping("/types")
	public String types(Model mode,Integer page,Integer id) {
		 Integer pages = 1;
		 Integer ids = 1;
	     if (page!=null) {
				pages=page;
			}
	     if (id!=null) {
	    	    ids=id;
			}
	     
	   //按时间排序的博客
		List<blog> blog= service.selectBlogtotype(pages, ids);
		//查询类型下博客总页数
		Integer pageall = (service.selecttypeBlogsSumservice(ids).size()/7)+1 ;
		
		//热门博客
		List<blog> blogre = service.selectblogreservice();
		
		//查询分类
		List<blogtype> types = service.selectblogtypeservice();
		
		
		mode.addAttribute("bloglist", blog);
		mode.addAttribute("pages", pageall);
		mode.addAttribute("cpage", pages);
		mode.addAttribute("bloglistre", blogre);
		mode.addAttribute("types", types);
		mode.addAttribute("id", ids);
		
		return "types";
	}
	
	
	@RequestMapping("/typessum")
	@ResponseBody
	public Object typessum(Model mode) throws JsonProcessingException {
		//查询饼状图所需type数据
		List<blogtype> type = service.selectblogtypeservice();
		
		//转换所需josn
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < type.size(); i++) {
			map.put(type.get(i).getType(),String.valueOf( type.get(i).getSum().size()));
		}	
		JsonMapper mapper = new JsonMapper();
		String json = mapper.writeValueAsString(map);
		
		return json;
	}
	
	
}

